﻿using CKS.Core.Framework;
using CKS.PLC.Action.System;
using FreeSql;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP50
{
    public class DB3051_Work51Action : SaveProcessingResults
    {
        /// <summary>
        /// 成品清洗投入
        /// </summary>
        /// <param name="_value"></param>
        public DB3051_Work51Action(DecodeValue _value) : base(_value)
        {
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {

            string Code = Value.GetLocationData(e.LocationId,1).ToString();
            var record = new CksProductionRecord()
            {
                ProductCode = Code,
               // ProductCleaningLoadingTime = DateTime.Now,
            };
            ProcessData(record);
            return base.AfterSaved(e);
        }

        private void ProcessData(CksProductionRecord data)
        {
            if (data.ProductCode.IsEmpty())
                return;
            var res = SplitSuffixGrade(data.ProductCode);
            data.ProductCode = res.Code;
            var record = GetRecordByProductCode(data.ProductCode);
            record.ProductCode = data.ProductCode;
          //  record.ProductCleaningLoadingTime = data.ProductCleaningLoadingTime;
            record.ProcessingStatus = 100;
            if (record.Id > 0)
                conn.Update<CksProductionRecord>()
                    .SetSource(record)
                    .UpdateColumns(a => new { a.ProductCode , a.ProcessingStatus 
                    //,a.ProductCleaningLoadingTime
                    })
                    .ExecuteAffrows();
            else
            {
                // 格式示例 PW 250624 0001  
                string dayCacheKey = $"PW{DateTime.Now.ToString("yyMMdd")}";
                var nextSeriaNumber = GetNextSerialNumber(dayCacheKey);
                record.SerialNumber = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";
                conn.Insert(record).ExecuteAffrows();
                conn.Update<CksKeyCache>()
                    .Set(a => a.MaxSerialNumber, nextSeriaNumber)
                   .Where(a => a.CacheKey == dayCacheKey).ExecuteAffrows();

            }
            EventBus.AddLog($"工站：OP50;{record.ProductCode} 保存完成  ");

        }

        private CksProductionRecord GetRecordByProductCode(string productCode)
        {
            var record = conn.Select<CksProductionRecord>()
                .Where(a => a.CreatedTime > DateTime.Now.AddYears(-1) && a.ProductCode == productCode).OrderByDescending(a => a.Id).First();
            if (record == null)
                record = new CksProductionRecord();
            return record;
        }
    }
}
